package com.testcase;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import org.htmlparser.Parser;
import org.htmlparser.filters.CssSelectorNodeFilter;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

import com.sensetecnic.client.SenseTecnicClient;
import com.sensetecnic.client.SenseTecnicException;
import com.testcase.settings.Settings;
import com.testcase.viewsen.SensorDescActivity;
import com.testcase.vincentApp.AndroidSensors;

public class SensorListClick extends ListActivity {
	
	private ArrayAdapter<String> adapter;
	private List<String> senList;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listsen);

        try {
        	//Parse the Sensor List full names using parse() then get titles only from titleOnly
	        senList = this.parse();
	        List<String> title = this.titleOnly(senList);
	        
	        //Setting Listadapter from the titles parsed
	        //R.layout.list_item defines the text of each item
	        setListAdapter(adapter = new ArrayAdapter<String>(this, R.layout.list_item, title));
	        ListView lv = getListView();
	        
	        //Add a listener to the top editbox which uses adapter.getFilter().filter(s)
	        //which filters the adapter based on the text entered
	        EditText eb = (EditText) findViewById(R.id.search_box);
	        eb.addTextChangedListener(new TextWatcher() {
	        	public void afterTextChanged(Editable s) {
	    	    }
	    	    public void beforeTextChanged(CharSequence s, int start, int count,
	    	            int after) {
	    	    }
	    	    public void onTextChanged(CharSequence s, int start, int before,
	    	            int count) {
	    	    	adapter.getFilter().filter(s);
	    	    }
	
	    	});
	        		
	        //Listener to the listadapter when an item is clicked
	        //get the position by comparing the item title clicked with the list to get the correct position
	        // TODO: Fix this listener to get the position of the item after filtering
	        /*
	         * When text is filtered the listadapter reorders the position
	         * so the listadapter chooses the incorrect position from the listview
	         * so currently I get the title name and check with with the list to get
	         * the position of the item
	         * 
	         * This can be a bug if there are duplicate titles
	         */
	        lv.setOnItemClickListener(new OnItemClickListener() {
	          public void onItemClick(AdapterView<?> parent, View view,
	              int position, long id) {
	        	  int ID = 0;
	        	  String sensTitle = adapter.getItem(position);
	        	  for(int i = 0; i < senList.size(); i++) {
	        		  if(senList.get(i).contains(sensTitle)) {
	        			  ID = i;
	        			  break;
	        		  }
	        	  }
	        	  
	        	  //Pass the data to other activites using putExtra
	        	  //Hashtable is an easy way to pass a list to other activities
	        	  Hashtable<String, List<String>> ht = new Hashtable<String, List<String>>();
	        	  ht.put("senList", senList);
	        	  //Pass the ActivityContext because the Activity cannot be referred in a listener
	        	  Intent intent = new Intent(getApplicationContext(), SensorDescActivity.class);
	        	  intent.putExtra("index", ID);
	        	  intent.putExtra("sensorList", ht);
	        	  intent.putExtra("title", sensTitle);
	        	  startActivity(intent);
	          }
	        });
        } catch (SenseTecnicException e) {
        	if(e.toString().contains("Unauthorized")) {
        		String[] incorrect = new String[] {"Click Menu. Enter a correct username/password combination. Click Back"};
        		setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, incorrect));
        	}
        	else {
        		String[] incorrect = new String[] {e.toString()};
        		setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, incorrect));
        	}
        } catch (ParserException e) {
        	String[] incorrect = new String[] {e.toString()};
    		setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, incorrect));
        }
	}
	
	//This creates the menu
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.settingsmenu, menu);
		return true;
	}
	
	//What to do when a menu option is clicked
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()) {
		case R.id.settings:
			Intent intent = new Intent(this, Settings.class);
			startActivity(intent);
			return true;
		case R.id.vincentApp:
			intent = new Intent(this, AndroidSensors.class);
			startActivity(intent);
			return true;
		default:
			return true;
		}
	}
	
	//Parse the Sense Tecnic Gallery and return a List<String> which contains all the sensors
	public List<String> parse() throws SenseTecnicException, ParserException {
		List<String> tmpList = new ArrayList<String>();
		SenseTecnicClient client = new SenseTecnicClient();
    	client.setStsBaseUrl("http://demo.sensetecnic.com/SenseTecnic");
    	
    	//Use Android preferences to get the username and password
    	//preferences is part of Android
    	SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
    	Resources reso = getResources();
    	String user = pref.getString(reso.getString(R.string.stsUsernameKey), null);
    	String pass = pref.getString(reso.getString(R.string.stsPasswordKey), null);

    	//Function I added to SenseTecnic client to return HTML as a String
    	String body = client.getHtml(user, pass, "/spring/sensors/");
    	
    	//Using HTML Parser library to parse the html.
    	//Parses the site for DIV tags with class "name"
    	Parser parser = new Parser(body);
    	CssSelectorNodeFilter cssFilter = 
    	    new CssSelectorNodeFilter("DIV.name");
    	NodeList nodes = parser.parse(cssFilter);
    	
    	for(int i=0; i < nodes.size(); i++) {
    		tmpList.add((nodes.elementAt(i).getFirstChild().toPlainTextString()).trim());
    	}
        
        return tmpList;
	}
	
	//Return on the title of each sensor
	public List<String> titleOnly(List<String> fullTitle) {
		List<String> title = new ArrayList<String>();
		for(int i=0; i < fullTitle.size(); i++) {
			int index;
			index = fullTitle.get(i).lastIndexOf("(");
			String tmpTitle = fullTitle.get(i).substring(0, index - 1);
			title.add(tmpTitle);
		}
		return title;
	}

}
